#include "ncurses.h"
#include "stdio.h"
#include "stdlib.h"
#define WIDTH 10
#define HEIGHT 22

typedef struct {char t,r; int x,y;} piece;

void printtab(char *tab, int w, int h){
    int i,buff=0;
    init_pair(0,0,0);
    init_pair(1,0,1);
    init_pair(2,0,2);
    init_pair(3,0,3);
    init_pair(4,0,4);
    init_pair(5,0,5);
    init_pair(6,0,6);
    init_pair(7,0,7);
    for(i=0 ; i<w*h ; i++){
        buff = tab[i];
        if(tab[i]<=7){
            attron(COLOR_PAIR(tab[i]));
            mvaddch(i/w,(i%w)*2,' ');
            addch(' ');
            attroff(COLOR_PAIR(tab[i]));
        }else{
            mvaddch(i/w,(i%w)*2,'[');
            addch(']');
        }
    }
}

void afficher(piece p, char* tab){
    int w=WIDTH+2;
    int h=HEIGHT+1;
    char *gtab = malloc(w*h*sizeof(char)); 
    int i;
    for(i=0 ; i<w*h ; i++){
        int x=i%(w),y=i/w;
        if( x==0 || x==w-1 || y==h-1){
            gtab[i]=8;
        }else{
            gtab[i]=tab[x-1+(y+4)*(w-2)];
            //gtab[i]=random()%8;
        }
    }
    printtab(gtab,w,h);
    refresh();
}
 
void spawn(piece* p){
    char types[7] = {'I','O','T','L','J','Z','S'};
    char type = types[random()%7];
    p->t = types[random()%7];
    p->x = 3;
    p->y = 0;
    p->r = 0;
}

void game(){
    char tab[(WIDTH)*(HEIGHT+4)];
    char run=1;
    int i;
    for(i=0 ; i<WIDTH*(HEIGHT+4) ; i++){
        tab[i]=0;
    }
    piece p;
    spawn(&p);
    while(run){
        afficher(p,tab);
    }
}

int main(){
    srand(time(NULL));
    initscr();
    start_color();
    game();
    getch();
    endwin();
    return 0;
}
